package com.northwind.serviceImpl;

import com.northwind.dao.CategoryMapper;
import com.northwind.entity.Category;
import com.northwind.entity.CategoryExample;
import com.northwind.service.CategoryService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    CategoryMapper categoryMapper;
    @Override
    public HashMap<String, Object> queryAllPage(Integer page, Integer rows) {
        HashMap<String, Object> map = new HashMap<>();
        //前台接收的参数 page当前页 rows每页展示的数据量
        //后台返回 page当前页 records总条数 total总页数 rows数据集合
        map.put("page",page);
        //创建条件对象
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andLevelsEqualTo("1");
        //总条数
        int records = categoryMapper.selectCountByExample(categoryExample);
        map.put("records",records);
        //总页数=总条数/每页展示条数，除不尽+1
        int total = records % rows == 0 ?records/rows:records/rows+1;
        map.put("total",total);
        //分页查询数据  1.条件 2.分页对象
        List<Category> categories = categoryMapper.selectByExampleAndRowBounds(categoryExample, new RowBounds((page - 1) * rows, rows));
        map.put("rows",categories);
        return map;
    }

    @Override
    public void add(Category category) {
        category.setId(UUID.randomUUID().toString());
        category.setLevels("1");
        category.setParentId(null);
        categoryMapper.insert(category);
    }

    @Override
    public void delete(Category category) {
        //在一级类别存在的前提下不能删除
        categoryMapper.delete(category);
    }

    @Override
    public void update(Category category) {
        categoryMapper.updateByPrimaryKeySelective(category);
    }

    @Override
    public HashMap<String, Object> queryByTwoCategory(Integer page, Integer rows, String parentId) {
        HashMap<String, Object> map = new HashMap<>();
        //前台接收的参数 page当前页 rows每页展示的数据量
        //后台返回 page当前页 records总条数 total总页数 rows数据集合
        map.put("page",page);
        //创建条件对象
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andParentidEqualTo(parentId);
        //总条数
        int records = categoryMapper.selectCountByExample(categoryExample);
        map.put("records",records);
        //总页数=总条数/每页展示条数，除不尽+1
        int total = records % rows == 0 ?records/rows:records/rows+1;
        map.put("total",total);
        //分页查询数据  1.条件 2.分页对象
        List<Category> categories = categoryMapper.selectByExampleAndRowBounds(categoryExample, new RowBounds((page - 1) * rows, rows));
        map.put("rows",categories);
        return map;
    }
}
